package es.uem.sudoku;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;


public class Game extends Activity {

	private static final String TAG = "Sudoku";
		
	public static final String KEY_DIFFICULTY = "es.uem.sudoku.difficulty";
	public static final int DIFFICULTY_EASY = 0;
	public static final int DIFFICULTY_MEDIUM = 1;
	public static final int DIFFICULTY_HARD = 2;

	private int puzzle[] = new int[9 * 9];

	private PuzzleView puzzleView;

	private final String easyPuzzle = "360000000004230800000004200"
			+ "070460003820000014500013020" + "001900000007048300000000045";
	private final String mediumPuzzle = "650000070000506000014000005"
			+ "007009000002314700000700800" + "500000630000201000030000097";
	private final String hardPuzzle = "009000000080605020501078000"
			+ "000000700706040102004000000" + "000720903090301080000000600";

	//private final int used[][][] = new int[9][9][];

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate");
		// By default easy difficulty
		int diff = getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_EASY);
		puzzle = getPuzzle(diff);
		//calculateUsedTiles();

		puzzleView = new PuzzleView(this);
		setContentView(puzzleView);
		puzzleView.requestFocus();
	}
	

	private int[] getPuzzle(int diff) {
		String puz;
		// TODO: Continue last game
		switch (diff) {
		case DIFFICULTY_HARD:
			puz = hardPuzzle;
			break;
		case DIFFICULTY_MEDIUM:
			puz = mediumPuzzle;
			break;
		case DIFFICULTY_EASY:
		default:
			puz = easyPuzzle;
			break;
		}
		return fromPuzzleString(puz);
	}


	static protected int[] fromPuzzleString(String string) {
		int[] puz = new int[string.length()];
		for (int i = 0; i < puz.length; i++) {
			puz[i] = string.charAt(i) - '0';
		}
		return puz;
	}

	private int getTile(int x, int y) {
		return puzzle[y * 9 + x];
	}

	private void setTile(int x, int y, int value) {
		puzzle[y * 9 + x] = value;
	}

	protected String getTileString(int x, int y) {
		int v = getTile(x, y);
		if (v == 0)
			return "";
		else
			return String.valueOf(v);
	}

	protected void showKeypadOrError(int x, int y) {
		
			Intent intent = new Intent("es.uem.sudoku.keypad");
			startActivityForResult(intent,1);
			
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
				
		int tile;
		
		if (requestCode == 1) {
			// ---if the result is OK---
			if (resultCode == RESULT_OK) {						
				tile = data.getIntExtra("tile", 0);	
				//Log.d(TAG, "Keypad return=" + String.valueOf(tile));
				puzzleView.setSelectedTile(tile);
				
				
			}
			
		}
	}
	
	protected boolean setTileIfValid(int x, int y, int value) {		
		
		setTile(x, y, value);		
		
		return true;
	}

}
